First Steps with Python

Source: learnpython.org

List comprehensions


In [1]:
sentence = 'the quick brown fox jumps over the lazy dog'
words = sentence.split()
word_lengths = [len(word) for word in words if 'the' != word]
print(word_lengths)


[5, 5, 3, 5, 4, 4, 3]

Variable amount of parameters


In [2]:
def foo(first, second, third, *therest):
    print('First: %s' % first)
    print('Second: %s' % second, end=' or ')
    print('Second: {}'.format(second))  # more modern approach
    print('Third: %s' % third)
    print('And all the rest... %s' % list(therest))
    return

print(foo(1,2,3,4,5))


First: 1
Second: 2 or Second: 2
Third: 3
And all the rest... [4, 5]
None

Variable amount of named parameters


In [3]:
def bar(first, second, third, **options):
    print('Options is a variable of {}.'.format(type(options)))
    if 'sum' == options.get('action'):
        print('The sum is: %d' % (first + second + third))

    if 'first' == options.get('number'):
        return first

result = bar(1, 2, 3, action='sum', number='first')
print('Result: %d' % result)


Options is a variable of <class 'dict'>.
The sum is: 6
Result: 1

Regular expressions


In [4]:
myExp = r'^(From|To|Cc).*?python-list@python.org'
import re
pattern = re.compile(myExp)
result = re.match(pattern, 'From sometextpython-list@python.org and some more')
if result:
    print(result)
    print('Whole result:', result.group(0), sep='\t')
    print('First part:', result.group(1), sep='\t')


<_sre.SRE_Match object; span=(0, 35), match='From sometextpython-list@python.org'>
Whole result:	From sometextpython-list@python.org
First part:	From

Sets


In [5]:
a = set(('Jake', 'John', 'Eric'))  # generate a set from a tuple
b = set(['John', 'Jill'])  # or generate a set from a list
print(a.intersection(b)) # in both sets
print(a.difference(b)) # in a but not in b
print(a.symmetric_difference(b)) # distinct
print(a.union(b)) # joined set


{'John'}
{'Eric', 'Jake'}
{'Eric', 'Jake', 'Jill'}
{'Eric', 'Jake', 'Jill', 'John'}

JSON/Pickle serialization

Using JSON.
Properties of JSON serialization: json = {binary: false, humanReadable: true, pythonSpecific: false, serializeCustomClasses: false}


In [6]:
import json
json_string = json.dumps([1, 2, 3, 'a', 'b', 'c'])
print(json_string)
print(json.loads(json_string))

json_string = json.dumps([1, 2, 3, 'a', 'b', 'c'], indent=2, sort_keys=True, separators=(',', ':'))
print(json_string)


[1, 2, 3, "a", "b", "c"]
[1, 2, 3, 'a', 'b', 'c']
[
  1,
  2,
  3,
  "a",
  "b",
  "c"
]

write JSON to and from a file


In [7]:
writeFp = open('config.json', 'w')
json.dump({'b':1, 'a':2}, writeFp, sort_keys=True)
writeFp.close()
readFp = open('config.json', 'r')
for line in readFp:
    print(line)
readFp.close()

# separators without spaces reduce json file size
print(json.dumps({'b':1, 'a':2}, sort_keys=True, separators=(',', ':')))


{"a": 2, "b": 1}
{"a":2,"b":1}

Using cPickle, Python's proprietary object serialization method. With pickle, objects can be serialized.
Properties of pickle serialization: pickle = {binary: true, humanReadable: false, pythonSpecific: true, serializeCustomClasses: true}


In [8]:
import pickle # or cPickle for a faster implementation
pickled_string = pickle.dumps([1, 2, 3, 'a', 'b', 'c'])
print(pickle.loads(pickled_string), end='\n\n')

class MyTestClass:
   def say(self):
        return 'hello'

pickled_string = pickle.dumps(MyTestClass())
print('Pickled:\t{}\nUnpickled:\t{}\nInstance call:\t{}'.format(
        pickled_string, pickle.loads(pickled_string), pickle.loads(pickled_string).say()
     )
)


[1, 2, 3, 'a', 'b', 'c']

Pickled:	b'\x80\x03c__main__\nMyTestClass\nq\x00)\x81q\x01.'
Unpickled:	<__main__.MyTestClass object at 0x000000000410C828>
Instance call:	hello